//
//  SCPhotoView.m
//  PhotoAlbum
//
//  Created by Chao Sheng on 2021/12/8.
//

#import "SCPhotoView.h"
#import "SCBottomPopAlertVC.h"
#import "SCCameraPhotoViewController.h"

@interface SCPhotoView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate, UIViewControllerTransitioningDelegate>

@property (nonatomic, strong) NSMutableArray *selectedArray;

@end

@implementation SCPhotoView {
    NSMutableArray *_nPhotoList;
}

- (instancetype)initWithManager:(SCPhotoManager *)manager {
    if (self = [super init]) {
        
        self.manager = manager;
        
        [self setupUI];
        
        self.currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    }
    return self;
}

- (void)setupUI {
    [self addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(@0);
        make.width.mas_equalTo(self.manager.photoViewWidth-10);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
    
    [self reloadView];
}

- (NSIndexPath *)currentIndexPathInModel:(SCPhotoModel *)model {
    NSInteger row = [self.manager.selectedArray indexOfObject:model];
    return [NSIndexPath indexPathForRow:row inSection:0];
}

- (void)setManager:(SCPhotoManager *)manager {
    _manager = manager;
}

- (void)reloadView {
    self.selectedArray = self.manager.selectedArray.mutableCopy;
    if (self.selectedArray.count < self.manager.photoSelectedMax && self.manager.editEnble) {
        SCPhotoModel*model = [SCPhotoModel new];
        model.addPhoto = true;
        [self.selectedArray addObject:model];
    }
    
    [self updatePhotoViewHeight];
    [self.collectionView reloadData];
}

- (void)resetView {
    self.manager.selectedArray = self.manager.oldSelectedArray.mutableCopy;
    self.selectedArray = self.manager.selectedArray.mutableCopy;
    if (self.selectedArray.count < self.manager.photoSelectedMax && self.manager.editEnble) {
        SCPhotoModel*model = [SCPhotoModel new];
        model.addPhoto = true;
        [self.selectedArray addObject:model];
    }
    
    [self updatePhotoViewHeight];
    [self.collectionView reloadData];
}

#pragma mark - 更新高度
- (void)updatePhotoViewHeight {
    NSInteger rowCount = sc_PAD ? 4 : 3;
    CGFloat width = (self.manager.photoViewWidth-10)/rowCount;
    NSInteger count =  self.selectedArray.count / rowCount + ((self.selectedArray.count % rowCount)==0 ? 0 : 1);
    CGFloat h = count * width;
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(h);
    }];
}

#pragma mark - 更新数据
- (void)phtotViewDelegateHandle {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(scPhotoView:allPhotos:PhotosRecognitionCompletion:)]) {
        
        if (!self.manager.ocrEnable) {
            [self.delegate scPhotoView:self allPhotos:self.manager.selectedArray PhotosRecognitionCompletion:NO];
        } else {
            //异步开启识别调用
            [self.delegate scPhotoView:self allPhotos:self.manager.selectedArray PhotosRecognitionCompletion:YES];
        }
    }
    
    NSMutableArray *newPhotoList = @[].mutableCopy;
    NSMutableArray *delPhotoList = @[].mutableCopy;
    _nPhotoList = @[].mutableCopy;

    [self.manager.selectedArray enumerateObjectsUsingBlock:^(SCPhotoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![self.manager.oldSelectedArray containsObject:obj]) {
            //旧数组中不存在obj，表示新增的对象
            [newPhotoList addObject:obj];
        }
    }];
    [self.manager.oldSelectedArray enumerateObjectsUsingBlock:^(SCPhotoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![self.manager.selectedArray containsObject:obj]) {
            //新数组中不存在obj，表示删除了对象
            [delPhotoList addObject:obj];
        }
    }];
    if (self.delegate && [self.delegate respondsToSelector:@selector(scPhotoView:newPhotos:deletePhotos:)]) {
        [self.delegate scPhotoView:self newPhotos:newPhotoList deletePhotos:delPhotoList];
    }
    _nPhotoList = newPhotoList.mutableCopy;
}

#pragma mark - collectionView delegate & datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.selectedArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SCPhotoModel*model = self.selectedArray[indexPath.row];
    if (model.addPhoto) {
        SCPhotoAddCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCPhotoAddCell" forIndexPath:indexPath];
        return cell;
    } else {
        SCPhotoSubCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCPhotoSubCell" forIndexPath:indexPath];
        cell.photoModel = model;
        cell.manager = self.manager;
        sc_weak(self);
        cell.scDeletePhoto = ^(SCPhotoModel * _Nonnull model) {
            
            if ([weakself.manager.selectedArray containsObject:model]) {
                [weakself.manager.selectedArray removeObject:model];
                //每次选择后都更新序号
                for (NSInteger i = 0; i < weakself.manager.selectedArray.count ; i++) {
                    SCPhotoModel *model = weakself.manager.selectedArray[i];
                    model.selectedIndex = i+1;
                }
            }
            weakself.selectedArray = weakself.manager.selectedArray.mutableCopy;
            if (weakself.selectedArray.count < weakself.manager.photoSelectedMax) {
                SCPhotoModel*model = [SCPhotoModel new];
                model.addPhoto = true;
                [weakself.selectedArray addObject:model];
            }
            [weakself reloadCollection];
            
        };
        
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SCPhotoModel*model = self.selectedArray[indexPath.row];
    if (model.addPhoto) {
        //添加
        [self goAddPhoto];
    } else {
        //预览
        [self goPreviewVC:indexPath.row];
    }
    
    self.currentIndexPath = indexPath;
}

- (void)goAddPhoto {
    sc_weak(self);
    SCBottomPopAlertVC *alertvc = [[SCBottomPopAlertVC alloc] init];
    SCBottomPopAction *action1  = [[SCBottomPopAction alloc] actionWithTitle:@"从本地相册中选取" ActionType:SCBottomPopActionDefaultType SelectHandler:^{
        [weakself goPhotoListVC];
    }];
    [alertvc addAction:action1];

    SCBottomPopAction *action2  = [[SCBottomPopAction alloc] actionWithTitle:@"拍摄照片" ActionType:SCBottomPopActionDefaultType SelectHandler:^{

        [weakself goCameraVC];
    }];
    [alertvc addAction:action2];
    
    SCBottomPopAction *action4  = [[SCBottomPopAction alloc] actionWithTitle:@"取消" ActionType:SCBottomPopActionCancelType SelectHandler:^{
        
    }];
    [alertvc addAction:action4];
    
    [self.sc_currentViewController presentViewController:alertvc animated:YES completion:nil];

}

- (void)goPreviewVC:(NSInteger)index {
    //预览
    SCPhotoAlbumPreviewViewController *vc = [SCPhotoAlbumPreviewViewController new];
    vc.photoList = self.manager.selectedArray;
    vc.currentModelIndex = index;
    vc.manager = self.manager;
    vc.selectedIndex = index+1;
    vc.origin = 1;
  
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    nav.modalPresentationStyle = 0;
    nav.transitioningDelegate = self;

    [self.sc_currentViewController presentViewController:nav animated:YES completion:nil];
}

- (void)goPhotoListVC {
    SCPhotoAlbumListViewController *v = [SCPhotoAlbumListViewController new];
    v.manager = self.manager;
    sc_weak(self);
    v.scSelectCompletion = ^{
        weakself.selectedArray = weakself.manager.selectedArray.mutableCopy;
        if (weakself.selectedArray.count < weakself.manager.photoSelectedMax) {
            SCPhotoModel*model = [SCPhotoModel new];
            model.addPhoto = true;
            [weakself.selectedArray addObject:model];
        }
        // 刷新collectionview
        [weakself reloadCollection];
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:v];
    nav.modalPresentationStyle = 0;
    [self.sc_currentViewController presentViewController:nav animated:YES completion:^{
    }];
}

- (void)goCameraVC {
    
    SCCameraPhotoViewController *cameraVC = [[SCCameraPhotoViewController alloc] init];
    cameraVC.manager = self.manager;
    sc_weak(self);
    [cameraVC setScCameraCompletion:^{
        weakself.selectedArray = weakself.manager.selectedArray.mutableCopy;
        if (weakself.selectedArray.count < weakself.manager.photoSelectedMax) {
            SCPhotoModel*model = [SCPhotoModel new];
            model.addPhoto = true;
            [weakself.selectedArray addObject:model];
        }
        // 刷新collectionview
        [weakself reloadCollection];
    }];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cameraVC];
    nav.modalPresentationStyle = 0;
    [self.sc_currentViewController presentViewController:nav animated:YES completion:nil];
}

#pragma mark - 转场动画
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    SCPhotoPreviewPresentAnimationTransition *anim = [[SCPhotoPreviewPresentAnimationTransition alloc] initWithPresentTransitionType:SCTransitionPresentType photoView:self];
    return anim;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    SCPhotoPreviewPresentAnimationTransition *anim = [[SCPhotoPreviewPresentAnimationTransition alloc] initWithPresentTransitionType:SCTransitionDismissType photoView:self];
    return anim;
}

- (void)reloadCollection {

    [UIView performWithoutAnimation:^{
        [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    }];
    
    [self updatePhotoViewHeight];
    //数据处理回传(collection调用获取高清图的方法耗时异步处理，这里进行延时调用保证图片已经获取到)
    [self asynchWaitTime];
}

//延时判断图片是否已经获取完毕，递归调用
- (void)asynchWaitTime {
    BOOL wait = NO;
    for (SCPhotoModel *model in self.manager.selectedArray) {
        if (!model.highQualityImage) {
            wait = YES;
            break;
        }
    }
    if (wait) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self asynchWaitTime];
        });
    } else {
        [self phtotViewDelegateHandle];
    }
}

#pragma mark - 懒加载
- (UICollectionView *)collectionView {
    if(!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        NSInteger rowCount = sc_PAD ? 4 : 3;
        CGFloat width = (self.manager.photoViewWidth-10)/rowCount;
        CGFloat height = width;
        flowLayout.itemSize = CGSizeMake(width, height);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = UIColor.clearColor;
        if (@available(iOS 11,*)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [_collectionView registerClass:[SCPhotoSubCell class] forCellWithReuseIdentifier:@"SCPhotoSubCell"];
        [_collectionView registerClass:[SCPhotoAddCell class] forCellWithReuseIdentifier:@"SCPhotoAddCell"];
    }
    return _collectionView;
}

@end
